package com.shanghaionstar.nav;

import android.app.Activity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.shanghaionstar.BaseFragment;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.adapter.NavSearchItemGridViewAdapter;
import com.shanghaionstar.nav.presenter.NavMainPresenter;
import com.shanghaionstar.nav.service.AbstractMapActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by zhaoyang on 2017/7/20.
 */

public class NavSearchFragment extends BaseFragment{

    @BindView(R.id.nav_search_grid)
    GridView mNavSearchGrid;

    AbstractMapActivity mMapActivity;

    NavMainPresenter mMainPresenter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_nav_search;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initGridData();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mMapActivity = (AbstractMapActivity) activity;
        mMainPresenter = new NavMainPresenter(mMapActivity.getScheduler(), mMapActivity, mMapActivity.getMapHandler());
    }

    private void initGridData() {
        TypedArray ta = getResources().obtainTypedArray(R.array.gridItem_image);
        int[] gridImages = new int[ta.length()];
        for (int i = 0;i<ta.length();i++)
            gridImages[i] = ta.getResourceId(i, 0);

        ta.recycle();

        String[] gridTexts = getResources().getStringArray(R.array.griditem_info);

        loadAndShowGridItems(gridImages,gridTexts);
    }

    private void loadAndShowGridItems(int[] gridImages, final String[] gridTexts) {
        List<Map<String, Object>> items = new ArrayList<>();
        for (int i = 0; i < gridImages.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("grid_image", gridImages[i]);
            item.put("text_item_info", gridTexts[i]);
            items.add(item);
        }

        NavSearchItemGridViewAdapter adapter = new NavSearchItemGridViewAdapter(items, getActivity());
        mNavSearchGrid.setAdapter(adapter);
        mNavSearchGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mMainPresenter.onGridViewItemClick(position, gridTexts, parent.getChildAt(position).findViewById(R.id.grid_image));
            }
        });
    }
}
